package com.collectplus.express.parcel;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppLogic;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.menu.WebViewActivity;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.ParcelBillBean;
import com.collectplus.express.model.ParcelDetailBeanNew;
import com.collectplus.express.model.ParcelRouteBean;
import com.collectplus.express.model.SameCityPriceOrderBean;
import com.collectplus.express.order.OrderPayActivity;
import com.collectplus.express.tools.CollectPointUtils;
import com.shouhuobao.samecity.SameCityOrderActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import droid.frame.ui.dialog.BaseDialog;
import droid.frame.utils.android.MathUtils;
import droid.frame.utils.lang.Str;

/**
 * 包裹详情
 *
 * @author kaka <br/>
 *         2017年1月6日
 */
public class ParcelDetailActivity extends BaseActivity2 implements OnClickListener {
    private TextView mExpressCompany;
    private ParcelDetailBeanNew parcelDetail;
    private int parcelStatus;
    private int orderStatus;
    private TextView mCountDownView;
    private TextView payType;
    /**
     * 倒计时时间
     */
    private long countdownTime;
    // 从paassport过来要要滚到包裹状态
    private int from;
    private String parcelId = "";
    private CountDownTimer countDownTimer = null;
    private Timer timer = null;
    /**
     * 上门订单取消弹出异常原因
     */
    private BaseDialog cancelOrderDialog = null;
    private CheckBox exception1CB;
    private CheckBox exception2CB;
    private CheckBox exception3CB;
    private LinearLayout exceptionItem4;
    private EditText exceptionEt;
    private LinearLayout courierLL;
    private LinearLayout doorFee;
    private TextView doorFeeTv;

    @Override
    protected void findViewById() {
        setContentView(R.layout.parcel_detail_new);
        super.findViewById();
        getAppTitle().setCommonTitle("我的包裹");
        parcelId = getIntent().getStringExtra("parcelId");
        parcelStatus = getIntent().getIntExtra("parcelStatus", 0);
        orderStatus = getIntent().getIntExtra("orderStatus", 0);
        from = getIntent().getIntExtra("from", 0);
        parcelDetail = (ParcelDetailBeanNew) getIntent().getSerializableExtra("parcelDetailBean");
        if (parcelDetail != null) {
            initViewValue(parcelDetail);

        } else {
            if (!Str.isEmpty(parcelId)) {
                showLoadingDialog("");
                AppHttp.getInstance().getParcelDetailNew(parcelId, 0);
            } else {
                Bundle bundle = getIntent().getBundleExtra("parcelBundle");
                if (bundle != null) {
                    parcelId = bundle.getString("parcelId");
                    showLoadingDialog("");
                    AppHttp.getInstance().getParcelDetailNew(parcelId, 0);
                }
            }
        }

    }

    /**
     * 绑定view值
     *
     * @param parcel
     */
    protected void initViewValue(final ParcelDetailBeanNew parcel) {
        // 头部
        ImageView parcelPic = (ImageView) findViewById(R.id.parcel_goods_img);
        TextView orderTime = (TextView) findViewById(R.id.parcel_order_time);
        TextView bagCode = (TextView) findViewById(R.id.parcel_bag_code);
        TextView sendPoint = (TextView) findViewById(R.id.parcel_send_point);

        //火箭侠信息
        courierLL = (LinearLayout) findViewById(R.id.courier_ll);
        //火箭侠花名
        TextView courierName = (TextView) findViewById(R.id.courier_name_tv);
        if (isNotEmpty(parcel.getNickName())) {
            courierName.setText("火箭侠: " + parcel.getNickName());
        } else {
            courierName.setText("火箭侠: ");
        }

        findViewById(R.id.price_order_tv).setOnClickListener(this);

        findViewById(R.id.courier_phone_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + parcel.getPhone()));
                getContext().startActivity(intent);
            }
        });
        // 寄件人item
        View senderItem = findViewById(R.id.parcel_sender_item);
        TextView senderName = (TextView) findViewById(R.id.parcel_sender_name);
        TextView senderAddress = (TextView) findViewById(R.id.parcel_sender_address);
        TextView senderPhone = (TextView) findViewById(R.id.parcel_sender_phone);
        mExpressCompany = (TextView) findViewById(R.id.parcel_detail_express_code);

        //
        LinearLayout routeLayout = (LinearLayout) findViewById(R.id.parcel_route_parent);

        if (parcel != null && !Str.isEmpty(parcel.getParcelImgUrl())) {
            AppLogic.getInstance().loadImage(parcel.getParcelImgUrl(), parcelPic);
            parcelPic.setOnClickListener(this);
        }
        // 取消订单
        View cancelView = findViewById(R.id.parcel_order_cancel);
        cancelView.setOnClickListener(this);

        LinearLayout payItme = (LinearLayout) findViewById(R.id.parcel_pay_item);
        LinearLayout repayItme = (LinearLayout) findViewById(R.id.parcel_repay_item);
        LinearLayout billItme = (LinearLayout) findViewById(R.id.parcel_bill_item);
        LinearLayout fullView = (LinearLayout) findViewById(R.id.parcel_full_view);

        doorFee = (LinearLayout) findViewById(R.id.door_fee_ll);
        //        上门类型
        TextView doorType = (TextView) findViewById(R.id.door_type);
        if (isNotEmpty(parcel.getType())) {
            doorType.setText("上门费(" + parcel.getType() + ")");
        } else {
            doorType.setText("上门费");
        }
        //支付方式
        payType = (TextView) findViewById(R.id.parcel_pay_type);

        //上门费
        doorFeeTv = (TextView) findViewById(R.id.door_fee_tv);
        //优惠说明
        TextView limitedTimeFreeTv = (TextView) findViewById(R.id.limited_time_free_tv);

        if (isEmpty(parcel.getDiscount())) {
            limitedTimeFreeTv.setVisibility(View.GONE);
        }
        limitedTimeFreeTv.setText(parcel.getDiscount());
        if (parcel.getDiscountType() == 1) {
            doorFeeTv.getPaint().setAntiAlias(true);//抗锯齿
            doorFeeTv.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
            doorFeeTv.setText("￥" + parcel.getPrice());
        } else {
            doorFeeTv.setText("￥" + parcel.getPrice());
        }

        //路由分享
        Button parcelShareBtn = (Button) findViewById(R.id.parcel_shared_bt);
        parcelShareBtn.setOnClickListener(this);
        //查看电子面单
        TextView parcelCheckBtn = (TextView) findViewById(R.id.parcel_check_bill);
        parcelCheckBtn.setOnClickListener(this);

        final View routeItem = findViewById(R.id.route_information);

        //同城右上角标签
        TextView goodsAndWeightTv = (TextView) findViewById(R.id.goods_and_weight_tv);
        //同城支付详情
        findViewById(R.id.down_iv).setOnClickListener(this);

        // 已取消的订单
        if (orderStatus == Const.OrderStatus.canceled) {
            routeItem.setVisibility(View.GONE);
            cancelView.setVisibility(View.GONE);
            payItme.setVisibility(View.GONE);
            billItme.setVisibility(View.GONE);
            parcelCheckBtn.setVisibility(View.GONE);
            //上门处理
            visitHomeView(parcel, sendPoint, routeLayout, billItme, fullView);
            //同城处理
            sameCityView(parcel, goodsAndWeightTv, cancelView);
            // 补差价
        } else if (!Str.isEmpty(parcel.getOrderId2())) {
            repayItme.setVisibility(View.VISIBLE);
            payItme.setVisibility(View.GONE);
            billItme.setVisibility(View.GONE);
            parcelCheckBtn.setVisibility(View.GONE);
            cancelView.setVisibility(View.GONE);

            repayItme.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            LayoutParams fullViewParams = fullView.getLayoutParams();
            fullViewParams.height = repayItme.getMeasuredHeight();
            fullView.setLayoutParams(fullViewParams);

            routeInformationShow(routeLayout, parcel);
            if (Str.isEmpty(parcel.getExpressNumber())) {
                mExpressCompany.setText(parcel.getExpressCompanyName());
            } else {
                mExpressCompany.setText(parcel.getExpressCompanyName() + ":" + parcel.getExpressNumber());
            }
            TextView weight = (TextView) findViewById(R.id.parcel_over_weight);
            weight.setText("下单选择" + parcel.getWeight() + "kg,实际" + parcel.getReweight() + "kg");
            Button payView = (Button) findViewById(R.id.parcel_order_repay);
            payView.setText("立即支付￥" + parcel.getOrder2Cost());
            payView.setOnClickListener(this);
            //上门处理
            visitHomeView(parcel, sendPoint, routeLayout, billItme, fullView);
            //同城处理
            sameCityView(parcel, goodsAndWeightTv, cancelView);
        } else if (parcelStatus == Const.ParcelStatus.unpayed) {
            routeItem.setVisibility(View.GONE);
            payItme.setVisibility(View.VISIBLE);
            billItme.setVisibility(View.GONE);
            parcelCheckBtn.setVisibility(View.GONE);

            payItme.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            LayoutParams fullViewParams = fullView.getLayoutParams();
            fullViewParams.height = payItme.getMeasuredHeight();
            fullView.setLayoutParams(fullViewParams);

            mCountDownView = (TextView) findViewById(R.id.parcel_suplus_time);

            paytimeCountdown(mCountDownView, parcel.getRemainTime());
            // 倒计时定时器
            countDownTimer = new CountDownTimer(parcel.getRemainTime(), 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    paytimeCountdown(mCountDownView, millisUntilFinished);
                }

                @Override
                public void onFinish() {
                }
            };
            countDownTimer.start();

            TextView payView = (TextView) findViewById(R.id.parcel_order_pay);
            String payMomeyTv = String.format("待支付  ￥%s", this.money(parcel.getCost(), parcel.getCheapValue()));
            int end = payMomeyTv.indexOf(".");
            int start = payMomeyTv.indexOf('￥') + 1;
            SpannableString msp = new SpannableString(payMomeyTv);// 实际支付：
            msp.setSpan(new RelativeSizeSpan(2.0f), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            payView.setText(msp);
            payView.setOnClickListener(this);
            //上门处理
            visitHomeView(parcel, sendPoint, routeLayout, billItme, fullView);
            //同城处理
            sameCityView(parcel, goodsAndWeightTv, cancelView);
        }
        //上门状态，待揽收或揽收超时，显示取消按钮
        else if ((parcel.getCityWide() || parcel.getVisit()) && (parcelStatus == Const.ParcelStatus.visitParcel || parcelDetail.getRemainingTime() <= 0)) {
            if (parcelStatus == Const.ParcelStatus.unpayed || parcelStatus == Const.ParcelStatus.payed
                    || parcelStatus == Const.ParcelStatus.visitParcel) {
                cancelView.setVisibility(View.VISIBLE);
            } else {
                cancelView.setVisibility(View.GONE);
            }
            //上门处理
            visitHomeView(parcel, sendPoint, routeLayout, billItme, fullView);
            //同城处理
            sameCityView(parcel, goodsAndWeightTv, cancelView);
        } else if (parcelStatus == Const.ParcelStatus.payed) {//待投递，不知道是线上支付还是线下支付
            cancelView.setVisibility(View.VISIBLE);
            payItme.setVisibility(View.GONE);
            billItme.setVisibility(View.VISIBLE);
            parcelCheckBtn.setVisibility(View.VISIBLE);
            //上门处理
            //上门
            visitHomeView(parcel, sendPoint, routeLayout, billItme, fullView);
            //同城处理
            sameCityView(parcel, goodsAndWeightTv, cancelView);
        } else {
            cancelView.setVisibility(View.GONE);
            payItme.setVisibility(View.GONE);
            billItme.setVisibility(View.VISIBLE);
            parcelCheckBtn.setVisibility(View.VISIBLE);
            //上门
            visitHomeView(parcel, sendPoint, routeLayout, billItme, fullView);
            //同城处理
            sameCityView(parcel, goodsAndWeightTv, cancelView);
        }

        findViewById(R.id.parcel_order_copy).setOnClickListener(this);

        String sendTiem = getTime(parcel.getOrderTime());
        orderTime.setText("下单时间: " + sendTiem);
        if (isNotEmpty(parcel.getBagCode())) {
            bagCode.setText("投递编号: " + parcel.getBagCode());
        } else {
            bagCode.setText("投递编号: " + getString(R.string.parcel_nobag_code));
        }

        setReceiverValue(parcel);

        if (Str.isEmpty(parcel.getSenderName()) || Str.isEmpty(parcel.getSenderAddress()) || Str.isEmpty(parcel.getSenderPhone())) {
            senderItem.setVisibility(View.GONE);
        } else {
            senderName.setText(parcel.getSenderName());
            senderAddress.setText(parcel.getSenderAddress());
            senderPhone.setText(parcel.getSenderPhone());
        }

        // 从passport过来滚到物流栏
        if (from == 1) {
            // findViewById(R.id.parcel_page).measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    ScrollView scrollView = (ScrollView) findViewById(R.id.scorll_view);
                    int y = (int) routeItem.getY();
                    scrollView.smoothScrollTo(0, y);
                }
            };
            timer.schedule(task, 500);
        }
        // 联系客服
        findViewById(R.id.parcel_detail_service).setOnClickListener(this);
    }

    /**
     * 上门布局展示
     *
     * @param parcel
     */
    private void visitHomeView(final ParcelDetailBeanNew parcel, TextView sendPoint, LinearLayout routeLayout, LinearLayout billItme, LinearLayout fullView) {
        //上门
        if (parcel.getVisit()) {
            sendPoint.setText("投递方式: 火箭侠上门");
            courierLL.setVisibility(View.VISIBLE);
            doorFee.setVisibility(View.VISIBLE);
            //            doorFeeTv.setText(parcel.get);
        } else {
            if (!Str.isEmpty(parcel.getStationAddress())) {
                sendPoint.setText("投递点: " + parcel.getStationAddress());
            }
            courierLL.setVisibility(View.GONE);
            doorFee.setVisibility(View.GONE);
        }
        initPayedParcelData(parcelDetail, routeLayout, billItme, fullView);
    }

    /**
     * 同城布局更新
     *
     * @param parcel
     * @param goodsAndWeightTv
     */
    private void sameCityView(final ParcelDetailBeanNew parcel, TextView goodsAndWeightTv, View cancelView) {
        //同城
        TextView parcelMsgTv = (TextView) findViewById(R.id.parcel_msg_tv);
        LinearLayout payLL = (LinearLayout) findViewById(R.id.pay_ll);
        LinearLayout packageStatus = (LinearLayout) findViewById(R.id.package_status);
        if (parcel.getCityWide()) {
            if (parcelStatus == Const.ParcelStatus.unpayed || parcelStatus == Const.ParcelStatus.payed) {
                cancelView.setVisibility(View.VISIBLE);
            } else {
                cancelView.setVisibility(View.GONE);
            }
            goodsAndWeightTv.setVisibility(View.VISIBLE);
            goodsAndWeightTv.setText(parcel.getCategory() + " " + parcel.getShowWeight() + "kg");
            findViewById(R.id.parcel_send_ll).setVisibility(View.GONE);
            parcelMsgTv.setText("支付信息");
            packageStatus.setVisibility(View.GONE);
            courierLL.setVisibility(View.VISIBLE);
            initCityWideDate(parcel);
            if (parcelStatus == Const.ParcelStatus.unpayed) {
                payType.setVisibility(View.VISIBLE);
                payLL.setVisibility(View.GONE);
            } else {
                payType.setVisibility(View.GONE);
                payLL.setVisibility(View.VISIBLE);
            }
        } else {
            goodsAndWeightTv.setVisibility(View.GONE);
            payLL.setVisibility(View.GONE);
            packageStatus.setVisibility(View.VISIBLE);
        }
    }

    private void initPayedParcelData(ParcelDetailBeanNew parcel, LinearLayout routeLayout, LinearLayout billItme, LinearLayout fullView) {
        LinearLayout parceLitem = (LinearLayout) findViewById(R.id.parcel_cost_item);
        ImageView payIcon = (ImageView) findViewById(R.id.pay_icon);
        TextView payTv = (TextView) findViewById(R.id.pay_tv);
        if (parcel.getCityWide()) {
            parceLitem.setVisibility(View.GONE);
        }
        if ("2".equals(parcel.getPayType())) {
            if (parcel.getCityWide()) {
                payIcon.setImageResource(R.drawable.zhifubao_icon);
                payTv.setText("支付宝支付");
            }
            payType.setText("线上支付-支付宝支付");
            Drawable drawable = getContext().getResources().getDrawable(R.drawable.parcel_detail_postage);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            payType.setCompoundDrawables(drawable, null, null, null);

        } else if ("1".equals(parcel.getPayType())) {
            if (parcel.getCityWide()) {
                payIcon.setImageResource(R.drawable.wx_icon);
                payTv.setText("微信支付");
            }
            payType.setText("线上支付-微信支付");
            Drawable drawable = getContext().getResources().getDrawable(R.drawable.parcel_detail_postage);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            payType.setCompoundDrawables(drawable, null, null, null);

        } else if ("0".equals(parcel.getPayType())) {
            parceLitem.setVisibility(View.GONE);
        } else if ("3".equals(parcel.getPayType())) {
            parceLitem.setVisibility(View.GONE);
            payType.setText("邮票支付-" + parcel.getStampName());
            payTv.setText("邮票支付-" + parcel.getStampName());
            payIcon.setImageResource(R.drawable.stamp_item_icon);
            Drawable drawable = getContext().getResources().getDrawable(R.drawable.stamp_item_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            payType.setCompoundDrawables(drawable, null, null, null);
        } else {
            payType.setText("在线支付");
            Drawable drawable = getContext().getResources().getDrawable(R.drawable.parcel_detail_postage);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            payType.setCompoundDrawables(drawable, null, null, null);
        }

        routeInformationShow(routeLayout, parcel);
        if (Str.isEmpty(parcel.getExpressNumber())) {
            mExpressCompany.setText(parcel.getExpressCompanyName());
        } else {
            mExpressCompany.setText(parcel.getExpressCompanyName() + "  " + parcel.getExpressNumber());
        }

        // 设置剩余高度
        billItme.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        LayoutParams fullViewParams = fullView.getLayoutParams();
        fullViewParams.height = billItme.getMeasuredHeight();
        fullView.setLayoutParams(fullViewParams);
    }

    /**
     * 同城支付费用明细
     */
    private void initCityWideDate(ParcelDetailBeanNew parcel) {
        SameCityPriceOrderBean descJsonBeans = parcel.getDescJson();
        if (descJsonBeans == null) {
            return;
        }
        TextView payMoneyTv = (TextView) findViewById(R.id.pay_money_tv);
        TextView basePriceTv = (TextView) findViewById(R.id.base_price_tv);
        TextView distanceTv = (TextView) findViewById(R.id.distance_tv);
        TextView distancePriceTv = (TextView) findViewById(R.id.distance_price_tv);
        TextView weightTv = (TextView) findViewById(R.id.weight_tv);
        TextView weightPriceTv = (TextView) findViewById(R.id.weight_price_tv);
        payMoneyTv.setText("￥" + descJsonBeans.getTotalPrice());
        basePriceTv.setText("￥" + descJsonBeans.getStartPrice());
        distanceTv.setText(descJsonBeans.getDistance() + "公里");
        distancePriceTv.setText("￥" + descJsonBeans.getDistancePrice());
        weightTv.setText(descJsonBeans.getWeight() + "kg");
        weightPriceTv.setText("￥" + descJsonBeans.getWeightPrice());
    }

    /**
     * 收件人栏信息绑定
     *
     * @param parcel
     */
    private void setReceiverValue(ParcelDetailBeanNew parcel) {
        // 收件人item
        TextView receiverName = (TextView) findViewById(R.id.parcel_receiver_name);
        TextView receiverAddress = (TextView) findViewById(R.id.parcel_receiver_address);
        TextView receiverPhone = (TextView) findViewById(R.id.parcel_receiver_phone);

        TextView costView = (TextView) findViewById(R.id.parcel_transpot_cost);
        receiverName.setText(parcel.getReceiverName());
        receiverAddress.setText(parcel.getReceiverAddress());
        receiverPhone.setText(parcel.getReceiverPhone());
        costView.setText(parcel.getCost());
    }

    /**
     * 路由信息展示
     *
     * @param routeLayout
     * @param parcel
     */
    private void routeInformationShow(LinearLayout routeLayout, ParcelDetailBeanNew parcel) {
        ArrayList<ParcelRouteBean> routes = parcel.getRoutes();
        if (null != routes && routes.size() > 0) {
            // 添加item
            for (int position = 0; position < routes.size(); position++) {
                ParcelRouteBean route = routes.get(position);
                String updateTime = getTime(route.getUpdateTime());
                if (parcel.getCityWide()) {
                    View items = getLayoutInflater().inflate(R.layout.parcel_status_city_wide_item, null);
                    TextView statusProgress = (TextView) items.findViewById(R.id.parcel_status);
                    TextView time = (TextView) items.findViewById(R.id.parcel_status_time);
                    TextView status = (TextView) items.findViewById(R.id.parcel_status_content);
                    statusProgress.setText(route.getState());
                    time.setText(updateTime);
                    status.setText(route.getDescription());
                    poitView(items, routes, position);
                    routeLayout.addView(items);
                } else {
                    View item = getLayoutInflater().inflate(R.layout.parcel_status_item, null);
                    TextView time = (TextView) item.findViewById(R.id.parcel_status_time);
                    TextView status = (TextView) item.findViewById(R.id.parcel_status_content);
                    time.setText(updateTime);
                    status.setText(route.getDescription());
                    poitView(item, routes, position);
                    routeLayout.addView(item);
                }
            }
        }
    }

    private void poitView(View item, ArrayList<ParcelRouteBean> routes, int position) {
        ImageView poitView = (ImageView) item.findViewById(R.id.parcel_status_point);
        // 设置圆点颜色 调用的老版代码
        if (routes.size() == 1) {
            poitView.setImageResource(R.drawable.parcel_detail_dot2);
        } else {
            if (position == 0) {
                poitView.setImageResource(R.drawable.parcel_detail_dot1);
            } else if (position == 1) {
                poitView.setImageResource(R.drawable.parcel_detail_dot2);
            } else {
                // 中间图片随机展示
                int randomInt = new Random().nextInt(12) % 10 + 3;
                int resId = getContext().getResources().getIdentifier("parcel_detail_dot" + randomInt, "drawable", getContext().getPackageName());
                poitView.setImageResource(resId);
            }
        }
    }

    /**
     * 支付时间倒计时
     *
     * @param countDown
     * @param remainTime
     */
    private void paytimeCountdown(TextView countDown, long remainTime) {
        countdownTime = remainTime;
        String[] diffs = AppLogic.getInstance().timeDiffStr(remainTime);
        String timeText = "";
        if (diffs.length == 0) {
            timeText = "00分钟" + diffs[0] + "00秒";
        } else if (diffs.length == 1) {
            timeText = "00分钟" + diffs[0] + "秒";
        } else if (diffs.length == 2) {
            timeText = diffs[0] + "分钟" + diffs[1] + "秒";
        } else if (diffs.length == 3) {
            timeText = diffs[1] + "分钟" + diffs[2] + "秒";
        }
        int minuteEnd = timeText.indexOf("分");
        int sencondStart = timeText.indexOf("钟") + 1;
        int sencondEnd = timeText.indexOf("秒");
        SpannableString secondSp = new SpannableString(timeText);
        secondSp.setSpan(new TextAppearanceSpan(this, R.style.count_down_style), 0, minuteEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        secondSp.setSpan(new TextAppearanceSpan(this, R.style.count_down_style), sencondStart, sencondEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        countDown.setText(secondSp, TextView.BufferType.SPANNABLE);

    }

    /**
     * 实际支付结果
     *
     * @param bagMoney       投递袋结果
     * @param favorableMoney 邮票价格
     * @return 实际支付结果
     */
    private double money(String bagMoney, String favorableMoney) {
        double mMoney = MathUtils.sub(bagMoney, favorableMoney);
        if (mMoney <= 0) {
            return 0.01;
        }
        return mMoney;
    }

    /**
     * 格式化时间
     *
     * @param time
     * @return
     */
    private String getTime(long time) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return formatter.format(new Date(time));
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 查看电子面单
            case R.id.parcel_check_bill:
                if (parcelDetail != null) {
                    showLoadingDialog("正在加载");
                    AppHttp.getInstance().getParcelBill(parcelDetail.getOrderId());
                }

                break;
            // 支付
            case R.id.parcel_order_repay:
                Intent repayIntent = new Intent();
                repayIntent.setClass(this, OrderPayActivity.class);
                repayIntent.putExtra("orderId", parcelDetail.getOrderId2());
                repayIntent.putExtra("isCover", 1);
                startActivity(repayIntent);
                break;
            case R.id.parcel_order_pay:
                if (countdownTime <= 0) {
                    showToast("订单支付超时");
                    return;
                }
                if (parcelDetail.getCityWide()) {
                    Intent intent = new Intent(getContext(), SameCityOrderActivity.class);
                    intent.putExtra("orderId", parcelDetail.getOrderId());
                    getContext().startActivity(intent);
                } else {
                    Intent payIntent = new Intent();
                    payIntent.setClass(this, OrderPayActivity.class);
                    payIntent.putExtra("orderId", parcelDetail.getOrderId());
                    startActivity(payIntent);
                }
                break;
            // 点击查看大图
            case R.id.parcel_goods_img:
                if (!Str.isEmpty(parcelDetail.getParcelImgUrl())) {
                    Intent largeIntent = new Intent(this, LargePicturePreviewActivity.class);
                    largeIntent.putExtra("picUrl", parcelDetail.getParcelImgUrl());
                    startActivity(largeIntent);
                }
                break;
            // 复制地址
            case R.id.parcel_order_copy:
                if (parcelDetail != null && !Str.isEmpty(parcelDetail.getExpressNumber())) {
                    CollectPointUtils.copyTest(getContext(), parcelDetail.getExpressNumber());
                    showToast("复制成功");
                } else {
                    showToast("当前没有运单号");
                }
                break;
            // 取消订单
            case R.id.parcel_order_cancel:
                if ((parcelDetail.getVisit() && parcelStatus == Const.ParcelStatus.visitParcel) || (parcelDetail.getCityWide() && parcelStatus == Const.ParcelStatus.payed)) {
                    //type :1是上门，2是同城
                    if (parcelDetail.getVisit()) {
                        cancelDialog3(parcelDetail.getPrice(), 1);
                    } else if (parcelDetail.getCityWide()) {
                        cancelDialog3("", 2);
                    }

                } else if ((parcelDetail.getVisit() || parcelDetail.getCityWide()) && parcelStatus == Const.ParcelStatus.unpayed) {
                    DialogMgr.showOrderCancelDialog3(getContext(), parcelDetail.getOrderId(), parcelDetail.getParcelId(), parcelStatus);
                } else {
                    DialogMgr.showOrderCancelDialog3(getContext(), parcelDetail.getOrderId(), parcelDetail.getParcelId(), parcelStatus);
                }
                break;
            // 联系客服
            case R.id.parcel_detail_service:
                DialogMgr.showPhoneDialog(getContext(), null);
                break;
            //分享路由
            case R.id.parcel_shared_bt:
                if (Str.isEmpty(parcelId)) {
                    showToast("分享失败!");
                    return;
                }
                if (parcelStatus == Const.ParcelStatus.payed) {
                    showToast("完成投递后才可以分享包裹路由信息给收件人哦！");
                } else {
                    DialogMgr.parcelRouteShare(this, parcelId);
                }
                break;
            //异常原因1
            case R.id.exception_item1:
            case R.id.exception1_cb:
                exception1CB.setChecked(true);
                exception2CB.setChecked(false);
                exception3CB.setChecked(false);
                exceptionItem4.setVisibility(View.GONE);
                break;
            //异常原因2
            case R.id.exception_item2:
            case R.id.exception2_cb:
                exception1CB.setChecked(false);
                exception2CB.setChecked(true);
                exception3CB.setChecked(false);
                exceptionItem4.setVisibility(View.GONE);
                break;
            //其他原因
            case R.id.exception_item3:
            case R.id.exception3_cb:
                exception1CB.setChecked(false);
                exception2CB.setChecked(false);
                exception3CB.setChecked(true);
                exceptionItem4.setVisibility(View.VISIBLE);
                break;
            //上门确认取消
            case R.id.submit_tv:
                if (exception1CB.isChecked()) {
                    AppHttp.getInstance().orderCancel(parcelDetail.getOrderId(), parcelDetail.getParcelId(), 9, "");
                } else if (exception2CB.isChecked()) {
                    AppHttp.getInstance().orderCancel(parcelDetail.getOrderId(), parcelDetail.getParcelId(), 10, "");
                } else {
                    String exception = exceptionEt.getText().toString().trim();
                    if (isEmpty(exception)) {
                        AppHttp.getInstance().orderCancel(parcelDetail.getOrderId(), parcelDetail.getParcelId(), 11, "");
                    } else {
                        AppHttp.getInstance().orderCancel(parcelDetail.getOrderId(), parcelDetail.getParcelId(), 11, exception);
                    }
                }
                if (cancelOrderDialog != null) {
                    cancelOrderDialog.dismiss();
                }
                break;
            //费用明细
            case R.id.down_iv:
                LinearLayout sameCityMoneyDetail = (LinearLayout) findViewById(R.id.same_city_money_detail);
                if (sameCityMoneyDetail.getVisibility() == View.VISIBLE) {
                    sameCityMoneyDetail.setVisibility(View.GONE);
                } else {
                    sameCityMoneyDetail.setVisibility(View.VISIBLE);
                }
                break;
            //价格规则
            case R.id.price_order_tv:
                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("title", "计价规则");
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 上门和同城取消订单
     */
    public void cancelDialog3(String price, int type) {
        cancelOrderDialog = DialogMgr.showOrderCancelDialog4((BaseActivity2) getContext(), parcelDetail.getOrderId(), this, price, type);
        exception1CB = (CheckBox) cancelOrderDialog.findViewById(R.id.exception1_cb);
        exception2CB = (CheckBox) cancelOrderDialog.findViewById(R.id.exception2_cb);
        exception3CB = (CheckBox) cancelOrderDialog.findViewById(R.id.exception3_cb);
        exceptionItem4 = (LinearLayout) cancelOrderDialog.findViewById(R.id.exception_item4);
        exceptionEt = (EditText) cancelOrderDialog.findViewById(R.id.exception_et);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 电子面单
            case MsgID.parcel_bill:
                cancelLoadingDialog();
                AppResult<ParcelBillBean> biLLResult = JSON.parser(msg.obj, ParcelBillBean.class);
                if (biLLResult.isSuccess()) {
                    final ParcelBillBean billBean = biLLResult.getResult();
                    if (billBean != null) {
                        Intent intent = new Intent(ParcelDetailActivity.this, ParcelDigitalBillActivity.class);
                        intent.putExtra("parcelStatus", parcelStatus);
                        intent.putExtra("parcelBill", billBean);
                        intent.putExtra("parcelId", parcelId);
                        startActivity(intent);
                    }
                } else {
                    showToast(biLLResult.getMessage());
                }
                return false;
            // 包裹详情
            case MsgID.parcel_detail:
                cancelLoadingDialog();
                // onRefreshComplete();
                try {
                    final AppResult<ParcelDetailBeanNew> result = JSON.parser(msg.obj, ParcelDetailBeanNew.class);// 解析可能出现问题
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (result.isSuccess()) {
                                parcelDetail = result.getResult();
                                if (parcelDetail != null) {
                                    initViewValue(parcelDetail);
                                } else {
                                    showToast("当前没有数据");
                                    finish();
                                }
                            } else {
                                // 未知原因是否需要显示
                                showToast(result.getMessage());
                            }
                        }
                    });
                    break;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            // 订单取消
            case MsgID.order_cancel:
                cancelLoadingDialog();
                AppResult<?> result1 = JSON.parser(msg.obj);
                switch (result1.getStatus()) {
                    case 1:
                        getContext().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showToast("订单取消成功");
                                setResult(Activity.RESULT_OK);
                                finish();// 关闭当前Activity
                            }
                        });
                        break;
                    default:
                        showToast(result1.getMessage());
                        break;
                }
                return false;
            default:
                return super.handleMessage(msg);
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
    }
}
